#!coding=utf-8
'''
Created on 2014-5-23

@author: Administrator
'''
import time
from django.dispatch.dispatcher import receiver
from weixin.signals import wxsignal_subscribe_event, wxsignal_click_event,\
    wxsignal_text
from weixin.models import User
from weixin.send.service import send_text_msg
from weixin.api.common import getAccToken

@receiver(wxsignal_subscribe_event)
def process_subscribe_event(sender,**kwargs):
    print "wxsignal_subscribe_event"
    tmpopenid=kwargs['msg']['FromUserName']
    try:
        userext=User.objects.get(openid=tmpopenid)
    except:
        usertmp=User(openid=tmpopenid)
        usertmp.save()
    contval='亲，您终于来啦！！欢迎您关注天天惠，天天优惠享不停！！'
    send_text_msg(tmpopenid,contval);

@receiver(wxsignal_text)
def process_text_event(sender,**kwargs):
    return {"MsgType":"transfer_customer_service"}

@receiver(wxsignal_click_event)
def process_click_event(sender,**kwargs):
    if kwargs['msg']['EventKey']=="V1001_suggest":
        tmpopenid=kwargs['msg']['FromUserName']
        access_token=getAccToken()
        posturl = "https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=" + access_token   
        req=urllib2.urlopen(posturl)
        kfinfo=json.load(req);
        if len(kfinfo['kf_online_list'])==0:
            contval="您好，暂无客服在线，如果有需要帮助，请直接在微信留言。"
            send_text_msg(tmpopenid,contval);
            return {"MsgType":"transfer_customer_service"}
        else :
            contval="您好，微信客服正在为您服务，请问有什么需要帮助？"
            #指定wxid_9vc6zag3dj3811这个客服账号
            send_text_msg(tmpopenid,contval);
            return {"MsgType":"transfer_customer_service"}
    else:
        return {"MsgType":"transfer_customer_service"}


    